//
//  RemotePlaybackViewController.swift
//  ZhiTing
//
//  Created by macbook on 2022/5/6.
//
#if !(targetEnvironment(simulator))
import UIKit
import JXSegmentedView

class RemotePlaybackViewController: BaseViewController {

    var clickFullScreenCallback: (() -> ())?

    
    var myUID = ""
    var mypwd = ""
    var displayView: IJKSDLGLView?
    var dayArray = [TFDataListStatus]()
    var dataArray = [TFDataListModel]()
    var currentPlayingName = ""
    var currentPlayingSize = 0
    var userTouch = false
    var mfCachePospos: Float = 0
    var isPlaying = false
    //是否为竖屏
    var isPortrait = true
    
    private lazy var placehoderView = UIView().then {
        $0.backgroundColor = .black
    }

    private lazy var placehoderImg = ImageView().then {
        $0.image = .assets(.camera_placehoder_icon)
    }
    
    private lazy var placehoderLabel = Label().then {
        $0.text = "请选择播放的时间"//"视频加载中..."
        $0.textColor = .custom(.gray_94a5be)
        $0.font = .font(size: 14, type: .bold)
        $0.textAlignment = .center
    }
    
    //视频底部视图
    private lazy var downView = RemotePlaybackDownView().then {
        $0.backgroundColor = .clear
        $0.isHidden = true
    }

    private lazy var tipsLabel = Label().then {
        $0.text = "回放"//"视频加载中..."
        $0.textColor = .custom(.black_3f4663)
        $0.font = .font(size: 14, type: .medium)
    }
    
    private lazy var line = UIView().then {
        $0.backgroundColor = .custom(.gray_eeeeee)
    }

    
    lazy var tableView = UITableView(frame: .zero, style: .plain).then {
        $0.delegate = self
        $0.dataSource = self
        $0.backgroundColor = .custom(.gray_f6f8fd)
        $0.separatorStyle = .none
        $0.rowHeight = UITableView.automaticDimension
        //创建Cell
        $0.register(RemotePlaybackListCell.self, forCellReuseIdentifier: RemotePlaybackListCell.reusableIdentifier)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        getTFList()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
        if displayView != nil {
            playVideo()
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        pusePlayBack()
    }
    
    
    //横屏布局
    public func setupLandscapeUI(size: CGSize){
        isPortrait = false
        displayView?.removeFromSuperview()
        displayView = nil
        
        self.downView.fullScreenBtn.isSelected = true
        self.placehoderView.snp.remakeConstraints {
            $0.edges.equalToSuperview()
        }
        self.view.bringSubviewToFront(downView)

    }
    
    //竖屏布局
    public func setupPortraitUI(size: CGSize){
        isPortrait = true
        displayView?.removeFromSuperview()
        displayView = nil
        let cameraWidth = size.width
        let cameraHeight = cameraWidth * 2/3
        self.downView.fullScreenBtn.isSelected = false
        self.placehoderView.snp.remakeConstraints {
            $0.top.equalToSuperview()
            $0.left.right.equalToSuperview()
            $0.height.equalTo(cameraHeight)
        }
        self.view.bringSubviewToFront(downView)
        self.placehoderView.layoutIfNeeded()
        
    }
    
    deinit {
        //退出视频
        VSNet.shareinstance().stopPlayBack(self.myUID)
        displayView = nil
    }

    override func setupViews() {
        view.addSubview(placehoderView)
        placehoderView.addSubview(placehoderImg)
        placehoderView.addSubview(placehoderLabel)
        view.addSubview(downView)
        view.addSubview(tipsLabel)
        view.addSubview(line)
        view.addSubview(tableView)
        
        downView.slider.delegate = self
        downView.slider.currentProgressColor = .custom(.blue_3699ff)
        let img = UIImageView()
        img.contentMode = .scaleAspectFit
        img.image = .assets(.camera_slider_dot)
        img.isUserInteractionEnabled = true
        downView.slider.setControlSubView(img, size: CGSize(width: 15, height: 15))

        downView.clickCallback = {[weak self] tap in
            guard let self = self else {return}
            switch tap {
            case 0://全屏
                self.clickFullScreenCallback?()
            case 1://声音
                break
            case 2://播放
                if self.isPlaying {
                    //暂停播放
                    self.pusePlayBack()
                }else{
                    //恢复播放
                    self.resumePlay()
                }
            default:
                break
            }
            
        }
    }
    
    override func setupConstraints() {
        placehoderView.snp.makeConstraints {
            $0.top.equalToSuperview()
            $0.left.right.equalToSuperview()
            $0.height.equalTo(self.view.bounds.width * 2/3)
        }
        
        placehoderImg.snp.makeConstraints {
            $0.center.equalToSuperview()
            $0.width.equalTo(33.5)
            $0.height.equalTo(41.5)
        }
        
        placehoderLabel.snp.makeConstraints {
            $0.top.equalTo(placehoderImg.snp.bottom).offset(13.5)
            $0.centerX.equalToSuperview()
            $0.width.greaterThanOrEqualTo(100)
        }
        
        tipsLabel.snp.makeConstraints {
            $0.top.equalTo(placehoderView.snp.bottom).offset(15)
            $0.left.equalTo(15)
            $0.right.equalTo(-15)
        }
        
        line.snp.makeConstraints {
            $0.top.equalTo(placehoderView.snp.bottom).offset(40)
            $0.left.right.equalToSuperview()
            $0.height.equalTo(0.5)
        }
        
        downView.snp.makeConstraints {
            $0.bottom.equalTo(placehoderView)
            $0.left.right.equalToSuperview()
        }
        
        tableView.snp.makeConstraints {
            $0.top.equalTo(line.snp.bottom).offset(5)
            $0.left.right.bottom.equalToSuperview()
        }
    }
    
    private func getTFList(){
        VSNet.shareinstance().setControlDelegate(myUID, withDelegate: self)
        VSNetSendCommand.vsNetCommandGetRecordFile(withDID: myUID, user: "admin", pwd: mypwd, loginuse: "admin", loginpas: mypwd, pageSize: 500, pageIndex: 0)
    }
    
    private func playVideo(){//播放视频
            VSNet.shareinstance().startPlayBack(myUID, fileName: currentPlayingName, withOffset: 0, fileSize: currentPlayingSize, delegate: self, supportHD: 1)
            self.placehoderLabel.text = "视频加载中..."
            self.downView.playBtn.isSelected = false
            self.downView.isHidden = false
            self.view.bringSubviewToFront(self.downView)
//        }
 
    }
    
    private func stopVideo(){
        VSNet.shareinstance().stopPlayBack(self.myUID)

            self.placehoderLabel.text = "视频已停止"
            self.downView.isHidden = true
            self.isPlaying = false
//            self.displayView = nil
//            self.displayView?.removeFromSuperview()

    }
    
    private func pusePlayBack(){
        VSNet.shareinstance().pausePlayback(self.myUID, pause: 2)
        
        DispatchQueue.main.async {[weak self] in
            self?.downView.playBtn.isSelected = true
            self?.isPlaying = false
        }
    }
    
    private func resumePlay() {
        //0:暂停回放与录制 1:恢复回放与录制 2:暂停回放 3:恢复回放 4:暂停录制
        VSNet.shareinstance().pausePlayback(self.myUID, pause: 3)
        DispatchQueue.main.async {[weak self] in
            self?.downView.playBtn.isSelected = false
            self?.isPlaying = true
        }
    }
    private func setupGLView(){
        if displayView != nil {
            return
        }
        placehoderView.layoutIfNeeded()
        displayView = IJKSDLGLView(frame:placehoderView.frame)
        displayView?.backgroundColor = UIColor.black
        displayView?.isUserInteractionEnabled = true
        downView.isHidden = false
        isPlaying = true
        self.view.addSubview(displayView!)
        self.view.bringSubviewToFront(downView)

    }

}

// MARK: - VSNetControlProtocol
extension RemotePlaybackViewController: VSNetControlProtocol {
    func vsNetControl(_ deviceIdentity: String!, commandType comType: Int, buffer retString: String!, length: Int32, charBuffer buffer: UnsafeMutablePointer<CChar>!) {
        ZTLog("RemoteRecordFileListViewController VSNet返回数据 UID:\(deviceIdentity ?? "") comtype \(comType)")
        if comType == CGI_IEGET_RECORD_FILE && myUID == deviceIdentity {
            if retString.contains("record_name0[0]"){
                ZTLog(retString ?? "")
                let count: Int = Int(subValueByKeyString(key: "record_num0=", retString: retString)) ?? 0
                if count > 0 {
                    for i in 0 ..< count{
                        let tfModel = TFDataListModel()
                        let recordName = subValueByKeyString(key: "record_name0[\(i)]=", retString: retString)
                        tfModel.record_name = recordName
                        tfModel.record_size = Int(subValueByKeyString(key: "record_size0[\(i)]=", retString: retString)) ?? 0
                        let year = recordName.dropFirst(0).prefix(4)+"年"
                        let month = recordName.dropFirst(4).prefix(2)+"月"
                        let day = recordName.dropFirst(6).prefix(2)+"日"
                        tfModel.record_date_YMD = String(year + month + day)
                        //具体时分秒
                        tfModel.record_date_time = recordName.dropFirst(8).prefix(2) + ":" + recordName.dropFirst(10).prefix(2) + ":" + recordName.dropFirst(12).prefix(2)
                        //保存年月日
                        if dayArray.filter({$0.record_date_YMD == tfModel.record_date_YMD}).count == 0 {
                            let statusModel = TFDataListStatus()
                            statusModel.record_date_YMD = tfModel.record_date_YMD
                            statusModel.isOpen = false
                            dayArray.append(statusModel)
                        }
                        dataArray.append(tfModel)
                        
                        if i == count - 1{
                            //刷新页面
                            ZTLog(dayArray.count)
                            ZTLog(dataArray.count)
                            if dayArray.count > 0 {
                                dayArray[0].isOpen = true
                                DispatchQueue.main.async {[weak self] in
                                    self?.tableView.reloadData()
                                }
                            }
                        }
                    }
                }
            }else{
                DispatchQueue.main.async {[weak self] in
                    self?.showToast(string: "读取TF卡失败，请检查")
                }
            }
        }
    }
    
    //根据key截取内容
    private func subValueByKeyString(key: String, retString: String) -> String{
        let result = retString.components(separatedBy: key).last?.components(separatedBy: ";").first?.replacingOccurrences(of: "\"", with: "")
        return result ?? ""
    }
    
}
// MARK: - TFCardProtocol(TF卡视频播放回调)
extension RemotePlaybackViewController: TFCardProtocol {
    func tfyuvNotify(_ yuv: UnsafeMutablePointer<UInt8>!, length: Int32, width: Int32, height: Int32, timestamp: UInt32, szdid: String!, pos fpos: Float, cachePos fCachePospos: Float, vType nType: Int32) {
        
            if width == -100 {//防crash
                return
            }

            mfCachePospos = fCachePospos
            
            DispatchQueue.main.async {[weak self] in
                self?.downView.slider.setLoadProgressValue(CGFloat(fCachePospos))
                self?.setupGLView()
            }
            

                //buff 是解码出来的视频数据。要及时使用或者保存起来，出了作用域(跳出回调方法)后就会释放掉。
            var overlay : SDL_VoutOverlay = SDL_VoutOverlay(w: Int32(Int(width)), h: Int32(Int(height)), pitches: (UInt16(width),UInt16(width) / 2,UInt16(width) / 2), pixels: (yuv, yuv + Int(width * height), yuv + Int(width * height) * 5 / 4))
            self.displayView?.display(&overlay)
            
            if userTouch == false {
                DispatchQueue.main.async {[weak self] in
                    self?.downView.slider.setCurrentProgressValue(CGFloat(fpos))
                }
            }
        
    }
    
    func tfImageNotify(_ image: Any!, timestamp: Int, szdid: String!, pos fpos: Float, cachePos fCachePospos: Float) {
    }
    
    //ret 1 &&fpos == 1成功;  -1 失败
    func tfrecordNotify(_ ret: Int32, pos fpos: Float, szdid: String!) {
        if (fpos == 1 && ret == 1 ) {
//            [self saveVideo];
        }
    }

}

extension RemotePlaybackViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dayArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //高度自适应
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: RemotePlaybackListCell.reusableIdentifier, for: indexPath) as! RemotePlaybackListCell
        let model = dayArray[indexPath.row]
        let datas = dataArray.filter({$0.record_date_YMD == model.record_date_YMD})
        cell.dateLabel.text = model.record_date_YMD
        cell.datas = datas
        cell.isOpen = dayArray[indexPath.row].isOpen

        cell.isLastCell = indexPath.row == dayArray.count - 1
        cell.isFirstCell = indexPath.row == 0
        
        cell.openCallback = {[weak self] in
            self?.dayArray[indexPath.row].isOpen = !(self?.dayArray[indexPath.row].isOpen ?? false)
            DispatchQueue.main.async {[weak self] in
                self?.tableView.reloadData()
            }
        }
        
        cell.videoCallback = {[weak self] index in
            //刷新页面数据
            let currentModel = datas[index]
            for (_, allModel) in (self?.dataArray ?? [TFDataListModel()]).enumerated() {
                if currentModel.record_name == allModel.record_name && currentModel.record_size == allModel.record_size {
                    allModel.isChoose = true
                }else{
                    allModel.isChoose = false
                }
            }
            DispatchQueue.main.async {[weak self] in
                self?.tableView.reloadData()
            }
            //视频加载
            self?.currentPlayingName = datas[index].record_name
            self?.currentPlayingSize = datas[index].record_size
            self?.stopVideo()
            self?.playVideo()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
}

class TFDataListModel : BaseModel {
    
    var record_name = ""
    var record_size = 0
    //年月日 YY-MM-DD
    var record_date_YMD = ""
    //具体时分秒
    var record_date_time = ""
    //是否选中
    var isChoose = false
}

class TFDataListStatus : BaseModel {
    var record_date_YMD = ""
    var isOpen = false
}

extension RemotePlaybackViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

//MARK: - 进度条代理
extension RemotePlaybackViewController: FDMProgressViewDelegate {
    

    /// 进度条正在拖动时回调
    func progressView(_ progressView: FDMProgressView, didDraggingProgressView currentValue: CGFloat) {
        let pos: Float = Float(currentValue)
            var newPos = pos / mfCachePospos
            //拖动的进度不能超出缓冲的进度，比如缓冲进度是50%那么拖的就不能超过半个进度条（也就是50%）
            if pos >= mfCachePospos {
                newPos = 1.0
            }
            
            let time = VSNet.shareinstance().movePlaybackPos(myUID, pos: newPos)
            if time > 0{
                VSNet.shareinstance().setPlaybackPos(myUID, time: UInt(time))
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
                self?.userTouch = false
            }
        }
    
    /// 开始点击拖动视图时回调
    func progressView(_ progressView: FDMProgressView, didTouchBeginDragView currentValue: CGFloat) {
            userTouch = true
    }
    
    /// 停止点击拖动视图时回调
    func progressView(_ progressView: FDMProgressView, didTouchEndDragView currentValue: CGFloat) {
        
    }

}
#endif
